<?php require_once('Connections/locamedicadmin.php'); ?>

<?php include('userValidation.php'); ?>

<?php require_once('functions.php'); ?>


<?php

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

	$errors = array();

	$csrenumber = $_POST['csre_number'];
	$keywords = $_POST['keywords'];
	$manufid = $_POST['manufacture_id'];
	$locamedicnum = $_POST['locamedic_number'];
	$name = $_POST['name_FR'];
	$categoryid = $_POST['category_id'];
	$price = $_POST['price'];
	$details = $_POST['details_FR'];
	$taxable = isset($_POST['taxable']) ? "true" : "";
	$manuf = $_POST['manufacture_num'];
	
	if (strlen($name) == 0) { array_push($errors,  "Nom ne peut pas etre vide"); } 
	
	if (strlen($price) == 0) { 
		array_push($errors,  "Prix ne peut pas etre vide"); 
	} else if (!is_numeric($price)) {
		array_push($errors,  "Prix doit etre un nombre"); 
	} else if ($price < 0) {
		array_push($errors,  "Prix doit etre positif"); 
	}
	
	$serviceselected = false;
	$keys_serv = array_keys($_POST);
	foreach ($keys_serv as $key) {
		if (!$serviceselected || strstr($key,"service_")) {
			$serviceselected = true;
		}
	}
	
	if (!$serviceselected) {
		array_push($errors,  "Au moins un service doit etre selectionne"); 
	}
	
	if (strlen($details) == 0) { array_push($errors, "Details ne peut pas etre vide"); } 
	
	if (sizeof($errors) == 0) {
	
		$productId = getNextValSeq("product");
	
		$file = strtolower($_FILES["uploadimage"]["name"]);
		$ext = strtolower(substr($file,-3,3));
		$imagen = date("dmYHis").".".$ext;
		$target_path = "../images/csre/products/" . $imagen; 
	
		$filepdf = strtolower($_FILES["uploadpdf"]["name"]);
		$extpdf = strtolower(substr($filepdf,-3,3));
		$pdf = date("dmYHis").".".$extpdf;
		$target_path_pdf = "../pdf/" . $pdf; 
		
		if (!move_uploaded_file($_FILES['uploadpdf']['tmp_name'], $target_path_pdf)){
			$pdf = "";
		}
		
		if(move_uploaded_file($_FILES['uploadimage']['tmp_name'], $target_path)) {
	
			include('SimpleImage.php');
	
			$image = new SimpleImage();
			$image->load($target_path);
			$ancho = $image->getWidth();
			$alto = $image->getHeight();
			if ($ancho > 640 || $alto > 480) {
				if ($ancho > $alto) {
					$alto = 640 * $alto / $ancho;
					$ancho = 640;
					echo 'ancho mas que alto';
				} else { 
					$ancho = 480 * $ancho / $alto;
					$alto = 480;
					echo 'alto mas que ancho';
				}
				$image->resize($ancho, $alto);
				$image->save($target_path);
			}
	
		} else {
			echo "";
			$imagen = "";
		}
	
		$insertSQL = sprintf("INSERT INTO csre_product (product_id, csre_number, keywords, manufacture_id, 
			locamedic_number, name_FR, name_US, category_id, price, details_FR, details_US, taxable, image, pdf, manufacture_num ) VALUES 
			(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
						   $productId,
						   GetSQLValueString($csrenumber, "text"),
						   GetSQLValueString($keywords, "text"),
						   GetSQLValueString($manufid, "int"),
						   GetSQLValueString($locamedicnum, "text"),
						   GetSQLValueString($name, "text"),
						   GetSQLValueString(" ", "text"),
						   GetSQLValueString($categoryid, "int"),
						   GetSQLValueString($price, "double"),
						   GetSQLValueString($details, "text"),
						   GetSQLValueString(" ", "text"),
						   GetSQLValueString($taxable, "defined","1","0"),
						   GetSQLValueString($imagen, "text"),
						   GetSQLValueString($pdf, "text"),
						   GetSQLValueString($manuf, "text"));
	
		mysql_select_db($database_locamedicadmin, $locamedicadmin);
		$Result1 = mysql_query($insertSQL, $locamedicadmin) or die(mysql_error());
	
		$keys = array_keys($_POST);
		
		foreach ($keys as $key) {
			if (strstr($key,"service_")) {
				$serviceid = str_replace("service_","", $key);
				$insertSqlService = sprintf("INSERT INTO csre_prod_service (type_id, product_id) VALUES (%s, %s)", $serviceid, $productId);
				mysql_select_db($database_locamedicadmin, $locamedicadmin);
				$Result1 = mysql_query($insertSqlService, $locamedicadmin) or die(mysql_error());
			}
		}

		header("Location: product_list.php"); 
		
	}
	
	
  
}

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_manufacturelist = "SELECT * FROM csre_manufacture order by name_FR";
$manufacturelist = mysql_query($query_manufacturelist, $locamedicadmin) or die(mysql_error());
$row_manufacturelist = mysql_fetch_assoc($manufacturelist);
$totalRows_manufacturelist = mysql_num_rows($manufacturelist);

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_categorylist = "SELECT * FROM csre_category order by name_FR";
$categorylist = mysql_query($query_categorylist, $locamedicadmin) or die(mysql_error());
$row_categorylist = mysql_fetch_assoc($categorylist);
$totalRows_categorylist = mysql_num_rows($categorylist);

mysql_select_db($database_locamedicadmin, $locamedicadmin);
$query_service = "SELECT * FROM csre_serv_types";
$service = mysql_query($query_service, $locamedicadmin) or die(mysql_error());
$row_service = mysql_fetch_assoc($service);
$totalRows_service = mysql_num_rows($service);

?>







<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Locamedic CSRE Admin</title>
<link href="locamedicadmin.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="page">

	<?php include('sidebar.php'); ?>
	
	<!-- end sidebar -->
	<div id="content">
		<div align="center"><img src="images/page_image_5.jpg" alt="" /></div>
	  <div class="boxed">
			<h1 class="title2">Ajouter le produit</h1>
			
			<?php include('errors.php'); ?>
	  
            <form method="POST" enctype="multipart/form-data" name="form1" action="<?php echo $editFormAction; ?>">
              <table>
                <tr valign="baseline">
                  <td nowrap >CSRE #:</td>
                  <td><input type="text" name="csre_number" value="<?php echo getValor('csre_number'); ?>" size="50" maxlength="40"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Keywords:</td>
                  <td><input type="text" name="keywords" value="<?php echo getValor('keywords'); ?>" size="50"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Manufacture:</td>
                  <td>
				    <select name="manufacture_id">
				      <?php do {  ?>
				      	<option value="<?php echo $row_manufacturelist['manufacture_id']; ?>"
							<?php if (getValor('manufacture_id') == $row_manufacturelist['manufacture_id']) { echo "selected='selected'"; } ?>>
							<?php echo $row_manufacturelist['name_' . $lang]?>
						</option>
				      <?php } while ($row_manufacturelist = mysql_fetch_assoc($manufacturelist)); ?>
                    </select>
                  </td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Locamedic #:</td>
                  <td><input type="text" name="locamedic_number" value="<?php echo getValor('locamedic_number'); ?>" size="50" maxlength="40"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Name:</td>
                  <td><input type="text" name="name_FR" value="<?php echo getValor('name_FR'); ?>" size="50" maxlength="40"></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap >Category:</td>
                  <td>
				  	<select name="category_id">
                    <?php do {  ?>
	                    <option value="<?php echo $row_categorylist['category_id']; ?>"
							<?php if (getValor('category_id') == $row_categorylist['category_id']) { echo "selected='selected'"; } ?>>
							<?php echo $row_categorylist['name_' . $lang]?></option>
                    <?php } while ($row_categorylist = mysql_fetch_assoc($categorylist)); ?>
                    </select>
                  </td>
                </tr>
				<tr>
					<td>
						Manufacture #
					</td>
					<td>
						<input type="text" name="manufacture_num" value="<?php echo getValor('manufacture_num'); ?>" size="50" maxlength="10" />
					</td>
				</tr>
                <tr valign="baseline">
                  <td nowrap >Price:</td>
                  <td><input type="text" name="price" value="<?php echo getValor('price'); ?>" size="20" maxlength="10" ></td>
                </tr>
				<tr>
					<td>
						Taxable:
					</td>
					<td>
						<input type="checkbox" name="taxable" value="1" <?php if (isset($_POST['taxable'])) { echo "checked='checked'"; } ?> />
					</td>
				</tr>
                <tr valign="baseline">
                  <td nowrap >Details:</td>
                  <td><textarea type="text" name="details_FR" size="32" cols="40" rows="4"><?php echo getValor('details_FR'); ?></textarea></td>
                </tr>
				<tr>
					<td>Service</td>
					<td>
						<table>
							<?php do { ?>
						 	<tr>
								<td>
									<input type="checkbox" name="service_<?php echo $row_service['type_id']; ?>" 
									<?php if (isset($_POST['service_' . $row_service['type_id']])) { echo "checked='checked'"; } ?> />
								</td>
								<td><?php echo $row_service['description']?></td>
							</tr>

						  <?php } while ($row_service = mysql_fetch_assoc($service)); ?>
						</table>
					</td>
				</tr>
				<tr>
					<td align="left">Image</td>
					<td><input type="file" name="uploadimage" /></td>
				</tr>
				<tr>
					<td align="left">PDF</td>
					<td><input type="file" name="uploadpdf" /></td>
				</tr>
              </table>
			  <div class="botonera">
			  	<input type="submit" value="Enregistrer">
				<input type="button" onclick="if (confirm('Etes-vous sur de vouloir annuler?')) { window.location='product_list.php' }" value="Annuler" />
			  </div>
              <input type="hidden" name="MM_insert" value="form1">
        </form>
            <p>&nbsp;</p>
	  </div>
  </div>
	<!-- end content -->
	<div style="clear: both;">&nbsp;</div>
</div>
<!-- end page -->

<?php include('footer.php'); ?>

</body>
</html>
<?php
mysql_free_result($manufacturelist);

mysql_free_result($categorylist);

mysql_free_result($service);

?>
